<?php
declare (strict_types = 1);

namespace app\command;

use app\api\services\SupplyService;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use app\common\models\Supply\SupplyMessagePool as messagePoolModel ;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class SupplyMessagePool extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('supply:message:pool')
            ->setDescription('the message:pool command');
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    protected function execute(Input $input, Output $output)
    {
        $ret = SupplyService::getInstance()->messagePoolList();
        if(empty($ret)){
            return false;
        }
        if($ret['status'] != 200 || empty($ret['data'])){
            return false;
        }
        $data = [
            'msg' => json_encode($ret,256),
        ];
        messagePoolModel::getInstance()->insert($data);
        //消息枚举值：1-订单状态变更,2-订单发货，3-售后订单状态变更，4-商品信息、状态变更通知,5-商品删除通知,6-商品规格删除通,7-商品规格变更通知,
        //8-选品库商品删除通知,9-选品库商品添加通知,10-添加选品库商品通知,11-删除选品库商品通知,12-选品库商品价格变更通知，20-创建订单
        foreach($ret['data'] as $v){
            try{
                $arr = json_decode($v['content'],true);
                switch ($v['enumNum']){
                    case 1:
                    case 2:
                        SupplyService::getInstance()->changeOrder($v);
                        break;
                    case 6:
                        SupplyService::getInstance()->delGoodsSku($arr['spuId']);
                        break;
                    case 4:
                    case 7:
                        SupplyService::getInstance()->updateGoods([$arr['spuId']]);
                        break;
                    case 5:
                    case 11:
                        SupplyService::getInstance()->delGoods($arr['spuId']);
                        break;
                    default:
                }
            }catch(\Exception $e){
                $output->writeln($e->getMessage());
            }

        }
        // 指令输出
        $output->writeln('message:pool');
    }
}
